import { defaults, get, has } from "lodash-es";
import { reactive } from "vue";

export function usePagination(
  cb: any,
  sizeOption: Array<number> = [10, 20, 50, 100, 200],
 ): any {
  const pagination = reactive({
   current: 1,
   total: 0,
   size: sizeOption[0],
   sizeOption,
   onPageChange: (page: number, extraData?: object) => {
    pagination.current = page
    return extraData ? cb(extraData) : cb()
   },
   onSizeChange: (size: number, extraData?: object) => {
   pagination.current = 1 
   pagination.size = size 
   return extraData ? cb(extraData) : cb() },
   setTotal: (total: number) => {
   pagination.total = total 
  }, reset() {
    pagination.current = 1 
    pagination.total = 0
    pagination.size = pagination.sizeOption[0]
    },
   }) 
  
  return [ 
   pagination, 
   pagination.onPageChange,
   pagination.onSizeChange,
   pagination.setTotal,
   ]
 }

export function useTable<T>(
  api: (params: any) => Promise<T>,
  params?: object | (() => object),
  options?: {
    path?: { data?: keyPath; total?: keyPath; page?: string; size?: string };
    immediate?: boolean;
  }
) {
  console.log(params,options,555);
  
  // 参数处理
  defaults(options, {
    path: { data: "data", total: "total", page: "page", size: "size" },
    immediate: false,
  });

  const [pagination, , , setTotal] = usePagination(() => refresh());
  const loading = ref(false);
  const data = ref([]);

  const refresh = (extraData?: object | (() => object)) => {
    const requestData = {
      [options?.path?.page as string]: pagination.current,
      [options?.path?.size as string]: pagination.size,
    };
    if (params) {
      if (typeof params === "function") {
        Object.assign(requestData, params());
      } else {
        Object.assign(requestData, params);
      }
    }
    loading.value = true;
    return api(requestData)
      .then((res) => {
        data.value = get(res, options!.path?.data, []);
        setTotal(get(res, options!.path?.total, 0));
        if (!has(res, options!.path?.data) || !has(res, options!.path?.total)) {
          console.warn("useTable：响应数据缺少所需字段");
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };

  options?.immediate && refresh();

  return [data as T, refresh, loading, pagination];
}
